package com.ay.weixin.fdc.boss.blog.event;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.controller.loader.FilePostForm;
import org.lizar.ioc.Container;
import org.lizar.util.StringHelper;

import com.ay.weixin.config.AppConfig;
import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.group.exception.ProjectNotExists;
import com.ay.weixin.config.group.exception.ProjectVarNotExists;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.boss.autoreply.event.ReplySetting;
import com.ay.weixin.fdc.boss.blog.db.BlogContentDao;
import com.ay.weixin.fdc.boss.blog.db.BlogDao;
import com.ay.weixin.fdc.boss.blog.domain.Blog;
import com.ay.weixin.fdc.boss.blog.domain.BlogContent;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;

public class MCBlog extends Event {
	private BlogDao			blog_dao;
	private BlogContentDao	blog_content_dao;
	
	public void init_property() throws Exception {
		this.blog_dao = ((BlogDao) Container.get(BlogDao.class));
		this.blog_content_dao = ((BlogContentDao) Container.get(BlogContentDao.class));
		
	}
	
	public String default_handling_path() {
		return "/mc/blog/*";
	}
	
	public void handle(EventLoader el) throws ServletException, IOException, ProjectNotExists, ProjectVarNotExists {
		Customer adm = (Customer) el.getSessionAttr("customer");
		if (adm == null) {
			el.response_to_root(CustomerLogin.login_path());
		} else{
			if (el.queryPathCheck(2, ""))
				index(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "add_new"))
				add_new(el);
			else if (el.queryPathCheck(2, "add"))
				add(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "visit"))
				visit(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "add_new_message"))
				add_new_message(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "update_message"))
				update_message(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "update"))
				update(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "update_status"))
				update_status(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "delete"))
				delete(el, adm.getWxprojectID());
			else if (el.queryPathCheck(2, "delete_message"))
				delete_message(el, adm.getWxprojectID());
			
			
		} 
	}
	
	private void delete_message(EventLoader el, long wxproject_id) throws IOException, ServletException {
		long id = el.getLong("message_id");
		long sa_id = el.getLong("sa_id");
		el.setParam("id", Long.valueOf(sa_id));
		try {
			this.blog_content_dao.delete(id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("operation.failed") + ":" + e.getLocalizedMessage());
			visit(el,wxproject_id);
			return;
		}
		
		visit(el,wxproject_id);
	}
	
	private void delete(EventLoader el, long wxproject_id) throws IOException, ServletException {
		long id = el.getLong("id");
		Blog blog = null;
		try {
			blog = this.blog_dao.getById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("operation.failed") + ":" + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		if (blog == null) {
			el.setAttr("msg", el.i18("mc.share.not.exists"));
			index(el,wxproject_id);
			return;
		}
		
		if (blog.getStatus() != Blog.STATUS.CLOSED.getValue()) {
			el.setAttr("msg", el.i18("mc.share.only.closed.canbe.deleted"));
			index(el,wxproject_id);
			return;
		}
		
		List<BlogContent> content_list = null;
		try {
			content_list = this.blog_content_dao.getBySAId(id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("operation.failed") + ":" + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		try {
			this.blog_content_dao.deleteBySaId(id);
			this.blog_dao.delete(id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("operation.failed") + ":" + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		if (content_list != null) {
			for (BlogContent content : content_list) {
				if (StringHelper.isNotNull(content.getPic_url())) {
					File pic = new File(el.getRealPath(content.getPic_url()));
					pic.delete();
				}
			}
		}
		el.setAttr("msg", el.i18("operation.success"));
		index(el,wxproject_id);
	}
	
	private void update_status(EventLoader el, long wxproject_id) throws IOException, ServletException {
		long id = el.getLong("id");
		int status = el.getInt("status", Blog.STATUS.OK.getValue());
		try {
			this.blog_dao.update_status(id, status);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("operation.failed") + ":" + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		el.setAttr("msg", el.i18("operation.success"));
		index(el,wxproject_id);
	}
	
	private void update_message(EventLoader el, long wxproject_id) throws IOException, ServletException, ProjectNotExists, ProjectVarNotExists {
		if (!el.isMultipartContent()) {
			el.text("invalid visit.");
			return;
		}
		FilePostForm file = el.parseFilePostForm(ProjectConfig.getLong(wxproject_id, "sys.max_image_file_size") * 1024L);
		file.setAllParamToAttr(el);
		String content = file.getStr("content");
		long id = file.getLong("id");
		long sa_id = file.getLong("sa_id");
		int pos = file.getInt("pos");
		el.setParam("id", Long.valueOf(sa_id));
		String msg = null;
		if (file.getErrorMsg() != null) {
			msg = file.getErrorMsg();
			el.setAttr("msg", msg);
			visit(el,wxproject_id);
			return;
		}
		
		BlogContent share_content = null;
		try {
			share_content = this.blog_content_dao.getById(id);
		} catch (SQLException e1) {
			e1.printStackTrace();
			el.setAttr("msg", el.i18("server.error") + ":" + e1.getLocalizedMessage());
			visit(el,wxproject_id);
			return;
		}
		if (share_content == null) {
			el.setAttr("msg", el.i18("mc.share.sharecontent.not.exists"));
			visit(el,wxproject_id);
			return;
		}
		
		String pic_file_name = null;
		FileItem pic = null;
		File pic_file = null;
		List<FileItem> items = file.getFileItems();
		for (FileItem it : items) {
			if (it.getFieldName().toLowerCase().equals("pic")) {
				pic = it;
			}
		}
		
		if (pic != null) {
			if (AppConfig.img_support_fix.get(StringHelper.postfix(pic.getName().toLowerCase())) == null) {
				msg = el.i18("mc.share.pic.format.not.corrent");
				el.setAttr("msg", msg);
				visit(el,wxproject_id);
				return;
			}
			pic_file_name = UUID.randomUUID().toString() + ".jpg";
			String file_path = ReplySetting.getImagePath(el, wxproject_id, pic_file_name);
			pic_file = new File(file_path);
			if (!pic_file.getParentFile().exists())
				pic_file.getParentFile().mkdirs();
			try {
				pic.write(pic_file);
			} catch (Exception e) {
				e.printStackTrace();
				msg = el.i18("image.save.failed");
				el.setAttr("msg", msg);
				visit(el,wxproject_id);
				return;
			}
			
		}
		
		if (content.length() > 4000) {
			msg = file.getErrorMsg();
			el.setAttr("msg", msg);
			visit(el,wxproject_id);
			return;
		}
		
		share_content.setContent(content);
		share_content.setPos(pos);
		String old_pic = share_content.getPic_url();
		if (pic != null)
			share_content.setPic_url(ReplySetting.getRelatImagePath(el, wxproject_id, pic_file_name));
		try {
			this.blog_content_dao.update(share_content);
		} catch (Exception e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_usercenter.server_error"));
			
			if (pic != null) {
				pic.delete();
			}
			
			visit(el,wxproject_id);
			return;
		}
		
		if ((pic != null) && (StringHelper.isNotNull(old_pic))) {
			File old_pic_file = new File(el.getRealPath(old_pic));
			old_pic_file.delete();
		}
		
		el.setAttr("msg", el.i18("operation.success"));
		visit(el,wxproject_id);
	}
	
	private void add_new_message(EventLoader el, long wxproject_id) throws IOException, ServletException, ProjectNotExists, ProjectVarNotExists {
		if (!el.isMultipartContent()) {
			el.text("invalid visit.");
			return;
		}
		FilePostForm file = el.parseFilePostForm(ProjectConfig.getLong(wxproject_id, "sys.max_image_file_size") * 1024L);
		file.setAllParamToAttr(el);
		String content = file.getStr("content");
		long sa_id = file.getLong("sa_id");
		el.setParam("id", Long.valueOf(sa_id));
		String msg = null;
		if (file.getErrorMsg() != null) {
			msg = file.getErrorMsg();
			el.setAttr("msg", msg);
			visit(el,wxproject_id);
			return;
		}
		String pic_file_name = null;
		FileItem pic = null;
		File pic_file = null;
		List<FileItem> items = file.getFileItems();
		for (FileItem it : items) {
			if (it.getFieldName().toLowerCase().equals("pic")) {
				pic = it;
			}
		}
		
		if (pic != null) {
			if (AppConfig.img_support_fix.get(StringHelper.postfix(pic.getName().toLowerCase())) == null) {
				msg = String.format(el.i18("fdc_usercenter.need_upload_business_card"), new Object[] { Keys.getStr("fdc_usercenter.image_post_fix_support") });
				el.setAttr("msg", msg);
				visit(el,wxproject_id);
				return;
			}
			pic_file_name = UUID.randomUUID().toString() + ".jpg";
			String file_path = ReplySetting.getImagePath(el, wxproject_id, pic_file_name);
			pic_file = new File(file_path);
			if (!pic_file.getParentFile().exists())
				pic_file.getParentFile().mkdirs();
			try {
				pic.write(pic_file);
			} catch (Exception e) {
				e.printStackTrace();
				msg = el.i18("fdc_usercenter.image.save.failed");
				el.setAttr("msg", msg);
				visit(el,wxproject_id);
				return;
			}
			
		}
		
		if (content.length() > 4000) {
			msg = file.getErrorMsg();
			el.setAttr("msg", msg);
			visit(el,wxproject_id);
			return;
		}
		BlogContent share_content = new BlogContent();
		share_content.setContent(content);
		
		share_content.setSa_id(sa_id);
		if (pic != null)
			share_content.setPic_url(ReplySetting.getRelatImagePath(el, wxproject_id, pic_file_name));
		try {
			share_content.setPos(this.blog_content_dao.getMaxPos(sa_id));
			this.blog_content_dao.insert(share_content);
		} catch (Exception e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("fdc_usercenter.server_error"));
			
			if (pic != null) {
				pic.delete();
			}
			
			visit(el,wxproject_id);
			return;
		}
		el.setAttr("msg", el.i18("operation.success"));
		visit(el,wxproject_id);
	}
	
	private void update(EventLoader el, long wxproject_id) throws IOException, ServletException, ProjectNotExists, ProjectVarNotExists {
		if (!el.isMultipartContent()) {
			el.text("invalid visit.");
			return;
		}
		FilePostForm post_form = el.parseFilePostForm(ProjectConfig.getLong(wxproject_id, "sys.max_image_file_size") * 1024L);
		long id = post_form.getLong("id");
		String name = post_form.getStr("name");
		String type = post_form.getStr("type");
		String template = post_form.getStr("template");
		
		el.setParam("id", Long.valueOf(id));
		
		if (StringHelper.isNull(name)) {
			el.setAttr("msg", el.i18("share.add.name.cannot.empty"));
			visit(el,wxproject_id);
			return;
		}
		
		if (StringHelper.isNull(template)) {
			el.setAttr("msg", el.i18("share.add.template.cannot.empty"));
			visit(el,wxproject_id);
			return;
		}
		
		if (StringHelper.isNull(type)) {
			el.setAttr("msg", el.i18("share.add.type.cannot.empty"));
			visit(el,wxproject_id);
			return;
		}
		
		Blog blog = null;
		System.out.println(id);
		try {
			blog = this.blog_dao.getById(id);
		} catch (SQLException e1) {
			e1.printStackTrace();
			el.setAttr("msg", el.i18("server.error") + ":" + e1.getLocalizedMessage());
			visit(el,wxproject_id);
			return;
		}
		
		if (blog == null) {
			el.setAttr("msg", el.i18("mc.share.not.exists"));
			index(el,wxproject_id);
			return;
		}
		
		String pic_file_name = null;
		FileItem pic = null;
		File pic_file = null;
		List<FileItem> items = post_form.getFileItems();
		for (FileItem it : items) {
			if (it.getFieldName().toLowerCase().equals("pic")) {
				pic = it;
			}
		}
		
		if (pic != null) {
			if (AppConfig.img_support_fix.get(StringHelper.postfix(pic.getName().toLowerCase())) == null) {
				el.setAttr("msg", el.i18("mc.share.image_post_fix_not_support"));
				visit(el,wxproject_id);
				return;
			}
			pic_file_name = UUID.randomUUID().toString() + ".jpg";
			String file_path = ReplySetting.getImagePath(el, wxproject_id, pic_file_name);
			pic_file = new File(file_path);
			if (!pic_file.getParentFile().exists())
				pic_file.getParentFile().mkdirs();
			try {
				pic.write(pic_file);
			} catch (Exception e) {
				e.printStackTrace();
				el.setAttr("msg", el.i18("fdc_usercenter.image.save.failed"));
				visit(el,wxproject_id);
				return;
			}
			
		}
		
		blog.setName(name);
		blog.setTemplate(template);
		blog.setType(type);
		blog.setUpdate_time(Calendar.getInstance().getTime());
		blog.setId(id);
		String old_pic = blog.getFace_pic_url();
		
		if (pic != null) {
			blog.setFace_pic_url(ReplySetting.getRelatImagePath(el, wxproject_id, pic_file_name));
		}
		try {
			this.blog_dao.update(blog);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("server.error") + ":" + e.getLocalizedMessage());
			
			if (pic != null) {
				pic.delete();
			}
			
			visit(el,wxproject_id);
			return;
		}
		
		if ((pic != null) && (StringHelper.isNotNull(old_pic))) {
			File old_pic_file = new File(el.getRealPath(old_pic));
			old_pic_file.delete();
		}
		
		el.setAttr("msg", el.i18("operation.success"));
		
		visit(el,wxproject_id);
	}
	
	private void visit(EventLoader el,long wxproject_id) throws IOException, ServletException {
		long id = el.getLong("id");
		Blog blog = null;
		try {
			blog = this.blog_dao.getById(id);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("operation.failed") + ":" + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		if (blog == null) {
			el.setAttr("msg", el.i18("mc.share.not.exists"));
			index(el,wxproject_id);
			return;
		}
		
		el.setAttr("share", blog);
		
		List content_list = null;
		try {
			content_list = this.blog_content_dao.getBySAId(blog.getId());
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("operation.failed") + ":" + e.getLocalizedMessage());
			index(el,wxproject_id);
			return;
		}
		
		el.setAttr("content_list", content_list);
		el.setAttr("status_list", Blog.STATUS.values());
		el.template("/WEB-INF/template/boss/blog/detail.vm");
	}
	
	private void add_new(EventLoader el) throws IOException, ServletException {
		el.setAttr("now_str", Calendar.getInstance().getTime().toLocaleString());
		el.setAttr("status_list", Blog.STATUS.values());
		el.template("/WEB-INF/template/boss/blog/add.vm");
	}
	
	private void add(EventLoader el, long wxproject_id) throws IOException, ServletException, ProjectNotExists, ProjectVarNotExists {
		if (!el.isMultipartContent()) {
			el.text("invalid visit.");
			return;
		}
		FilePostForm post_form = el.parseFilePostForm(ProjectConfig.getLong(wxproject_id, "sys.max_image_file_size") * 1024L);
		post_form.setAllParamToAttr(el);
		String name = post_form.getStr("name");
		String type = post_form.getStr("type");
		String template = post_form.getStr("template");
		
		if (StringHelper.isNull(name)) {
			el.setAttr("msg", el.i18("share.add.name.cannot.empty"));
			add_new(el);
			return;
		}
		
		if (StringHelper.isNull(template)) {
			el.setAttr("msg", el.i18("share.add.template.cannot.empty"));
			add_new(el);
			return;
		}
		
		if (StringHelper.isNull(type)) {
			el.setAttr("msg", el.i18("share.add.type.cannot.empty"));
			add_new(el);
			return;
		}
		
		String pic_file_name = null;
		FileItem pic = null;
		File pic_file = null;
		List<FileItem> items = post_form.getFileItems();
		for (FileItem it : items) {
			if (it.getFieldName().toLowerCase().equals("pic")) {
				pic = it;
			}
		}
		
		if (pic != null) {
			if (AppConfig.img_support_fix.get(StringHelper.postfix(pic.getName().toLowerCase())) == null) {
				el.setAttr("msg", el.i18("mc.share.image_post_fix_not_support"));
				add_new(el);
				return;
			}
			pic_file_name = UUID.randomUUID().toString() + ".jpg";
			String file_path = ReplySetting.getImagePath(el, wxproject_id, pic_file_name);
			pic_file = new File(file_path);
			if (!pic_file.getParentFile().exists())
				pic_file.getParentFile().mkdirs();
			try {
				pic.write(pic_file);
			} catch (Exception e) {
				e.printStackTrace();
				el.setAttr("msg", el.i18("fdc_usercenter.image.save.failed"));
				add_new(el);
				return;
			}
			
		}
		
		Blog blog = new Blog();
		blog.setStatus(Blog.STATUS.OK.getValue());
		blog.setName(name);
		blog.setTemplate(template);
		blog.setType(type);
		blog.setUpdate_time(Calendar.getInstance().getTime());
		if (pic != null)
			blog.setFace_pic_url(ReplySetting.getRelatImagePath(el, wxproject_id, pic_file_name));
		try {
			this.blog_dao.insert(blog);
		} catch (SQLException e) {
			e.printStackTrace();
			el.setAttr("msg", el.i18("server.error") + ":" + e.getLocalizedMessage());
			add_new(el);
			return;
		}
		
		el.setAttr("msg", el.i18("operation.success"));
		
		index(el,wxproject_id);
	}
	
	private void index(EventLoader el,long wxproject_id) throws IOException, ServletException {
		int status = el.getInt("status", Blog.STATUS.OK.getValue());
		List share_list = null;
		try {
			share_list = this.blog_dao.getByStatus(wxproject_id,status);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		el.setAttr("status", Integer.valueOf(el.getInt("status", Blog.STATUS.OK.getValue())));
		el.setAttr("share_list", share_list);
		el.setAttr("status_list", Blog.STATUS.values());
		el.template("/WEB-INF/template/boss/blog/index.vm");
	}
}